package com.core.family.admin.service.Impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.core.common.gen.BaseServiceImpl;
import com.core.common.manger.storage.IStorageRealm;
import com.core.family.admin.domain.FileStorage;
import com.core.family.admin.mapper.FileStorageMapper;
import com.core.family.admin.service.FileStorageService;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * 提供存储服务类，所有存储服务均由该类对外提供
 */
@Service
@Data
public class FileStorageServiceImpl extends BaseServiceImpl<FileStorageMapper, FileStorage> implements FileStorageService {


    private final IStorageRealm storageRealm;

    @Resource
    FileStorageMapper mapper;


    private FileStorage convert(IStorageRealm.FileMate fileMate) {

        FileStorage dbStorage = new FileStorage()
                .setFileDir(fileMate.getFileDir())
                .setFileKey(fileMate.getFileKey())
                .setFileType(fileMate.getFileType())
                .setFileLength("" + fileMate.getFileLength())
                .setFilePath(fileMate.getFilePath())
                .setFileUrl(fileMate.getFileUrl())
                .setFileMd5(fileMate.getFileMd5())
                .setStorageType(storageRealm.getActive());

        return dbStorage;
    }

    /***
     * 创建文件实体记录 如果存在则增加引用数，否则新增
     * @param inputStream
     * @param suffixName
     * @param contentLength
     * @return
     * @throws IOException
     */
    @Override
    public FileStorage createWithcheck(InputStream inputStream, String suffixName, long contentLength) throws IOException {
        FileStorage fileStorage = getIfAbsent(inputStream);
        if (Objects.isNull(fileStorage)) {
            fileStorage.setLinkCount(fileStorage.getLinkCount() + 1);
            updateById(fileStorage);
            return fileStorage;
        }
        IStorageRealm.FileMate fileMate = storageRealm.store(inputStream, suffixName, contentLength);
        fileStorage = convert(fileMate);
        save(fileStorage);

        return fileStorage;
    }

    /***
     * 删除 实际上是减少引用数
     * @param md5
     * @param id
     * @return
     */
    @Override
    public boolean removeBy(String md5, String id) {
        this.mapper.updateMinus(md5, id);
        return false;
    }

    @Override
    public FileStorage getByMd5(String id) {
        return this.mapper.selectById(id);
    }
}
